package com.leyou.item.service;

import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import com.leyou.item.pojo.SpecGroup;
import com.leyou.item.pojo.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SpecService {

    @Autowired
    private SpecGroupMapper specGroupMapper;

    @Autowired
    private SpecParamMapper specParamMapper;

    public List<SpecGroup> querySpecGroups(Long cid) {
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(cid);
        List<SpecGroup> specGroups = specGroupMapper.select(specGroup);

        // 查询规格参数到规格组
        specGroups.forEach(record -> {
            SpecParam specParam = new SpecParam();
            specParam.setGroupId(record.getId());
            List<SpecParam> specParams = specParamMapper.select(specParam);
            record.setSpecParams(specParams);
        });
        return specGroups;
    }

    public void addSpecGroup(SpecGroup specGroup) {
        specGroupMapper.insertSelective(specGroup);
    }

    public void updateSpecGroup(SpecGroup specGroup) {
        specGroupMapper.updateByPrimaryKey(specGroup);
    }

    public void deleteSpecGroup(Long id) {
        // 查询该规格组下的所有规格参数并删除
        List<SpecParam> specParams = querySpecParams(id, null, null, null);
        specParams.forEach(specParam -> {
            deleteSpecParam(specParam.getId());
        });
        // 再删除该规格组
        specGroupMapper.deleteByPrimaryKey(id);
    }

    public List<SpecParam> querySpecParams(Long gid, Long cid, Boolean searching, Boolean generic) {
        SpecParam specParam = new SpecParam();
        specParam.setGroupId(gid); // 规格组id
        specParam.setCid(cid); // 商品分类id
        specParam.setSearching(searching);// 是否可以查询
        specParam.setGeneric(generic);// 是否通用
        List<SpecParam> specParams = specParamMapper.select(specParam);
        return specParams;
    }

    public void addSpecParam(SpecParam specParam) {
        specParamMapper.insertSelective(specParam);
    }

    public void updateSpecParam(SpecParam specParam) {
        specParamMapper.updateByPrimaryKey(specParam);
    }

    public void deleteSpecParam(Long id) {
        specParamMapper.deleteByPrimaryKey(id);
    }

}
